﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Net.Http;
using System.IO;
using System.Net.Http.Headers;

namespace KyFileSyncTransfer.Api.Common
{
    public static class BaseUtility
    {
        public static string GetDirectoryFromConfig(string cfgName)
        {
            string dir = ConfigurationManager.AppSettings[cfgName];
            if (string.IsNullOrEmpty(dir))
            {
                return null;
            }

            if (dir.Contains('~'))
            {
                dir = HttpContext.Current.Server.MapPath(dir);
            }

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            return dir;
        }


        public static MultipartFormDataContent CreateMultipartFormDataContent(MultipartFormDataContent content, string removeRootDir, string dir)
        {
            foreach (string file in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(file))
                {
                    byte[] fileBytes = File.ReadAllBytes(file);
                    var fileContent = new ByteArrayContent(fileBytes);
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name = "files",
                        FileName = file.Replace(removeRootDir, "")
                    };
                    fileContent.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(file));
                    fileContent.Headers.ContentLength = fileBytes.LongLength;
                    content.Add(fileContent);
                }
                else
                {
                    CreateMultipartFormDataContent(content, removeRootDir, file);
                }
            }
            return content;
        }

        public static void LoadFileDatas(Dictionary<string, byte[]> files, string path)
        {
            foreach (string file in Directory.GetFileSystemEntries(path))
            {
                if (File.Exists(file))
                {
                    files[file] = File.ReadAllBytes(file);
                }
                else
                {
                    LoadFileDatas(files, file);
                }
            }
        }

        public static void WriteLogToFile(string logDir, params string[] contents)
        {
            string logFilePath = Path.Combine(logDir, "KyFileSyncTransfer.log");
            if (File.Exists(logFilePath) && !File.GetLastWriteTime(logFilePath).Date.Equals(DateTime.Today))
            {
                File.Delete(logFilePath);
            }

            File.AppendAllLines(logFilePath, contents, System.Text.Encoding.UTF8);

        }

        public static bool ValidateToken(string token)
        {
            try
            {
                token = EncryptUtility.Decrypt(token);
                var tokenParts = token.Split(new[] { "-", string.Empty }, StringSplitOptions.RemoveEmptyEntries);
                if (tokenParts.Length != 2)
                {
                    return false;
                }
                if (tokenParts[0] == string.Join(string.Empty, "KyFileSyncTransfer.Api".OrderBy(c => c))) //对固定KEY进行排序然后比对
                {
                    long tokenTstamp = -1;
                    long svrTokenTimeStamp = GetTimeStamp();
                    if (long.TryParse(tokenParts[1], out tokenTstamp) && svrTokenTimeStamp - tokenTstamp <= 10) //时间戳<=10则视为有效
                    {
                        return true;
                    }
                }
            }
            catch
            { }

            return false;
        }

        public static string ReviseFileName(string fileName)
        {
            var regex = new System.Text.RegularExpressions.Regex("^\"+(?<name>.*)\"+$");
            var matchResult = regex.Match(fileName);
            if (matchResult != null && matchResult.Length > 0)
            {
                return matchResult.Groups["name"].Value;
            }
            return fileName;
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        private static long GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }




    }
}